import {size} from '@/app/utils';
import React,{useState,useEffect, useRef} from 'react';
import {
  View,
  Text,
  StatusBar,
  Alert
} from 'react-native';
import {
  CodeField,
  Cursor,
  useBlurOnFulfill,
  useClearByFocusCell,
} from 'react-native-confirmation-code-field';
import Button from '@/app/components/Button'
import { useSafeAreaInsets } from 'react-native-safe-area-context';
import {styles} from './style/LoginScreenCss'
import Headers from '@/app/components/header/Headers';
import { getwangjiPwdrenzheng,getEamilCode } from './serve'
import { useTranslation } from '@/app/utils/useTranslation';
import { useNavigation,useRoute } from "@react-navigation/native";
let ForgetPasswordStep2Screen = (props:any)=>{
    const { t } = useTranslation();
    const route:any = useRoute();
    const insets = useSafeAreaInsets();
    const navigation:any = useNavigation();
    interface Step2Params {
        code: string;
        loginName: string;
        name: string;
    }
    let [paramsData,setParamsData] = useState<Partial<Step2Params>>({});
    let [disabled,setDisabled] = useState(false);
    const [countdown, setCountdown] = useState(0);
    const timerRef = useRef<any>(null);

    function onNext(){
        if(!value){
            return global.$toast(t('t372'));
        }
        const codeRegex = /^\d{6}$/;
        if(!codeRegex.test(value)){
            return global.$toast(t('t373'));
        }
        let params = {
            ...paramsData,
            mobileCode:value,
        }
        if(paramsData.name=='wangjimima'){
            setDisabled(true);
            getwangjiPwdrenzheng(params).then(()=>{
                setDisabled(false);
                navigation.navigate('pages/auth/ForgetPasswordStep3Screen',params);
            }).catch(err=>{
                setDisabled(false);
            })
        }else{
            navigation.navigate('pages/auth/ForgetPasswordStep3Screen',params);
        }
    }

    const onResendCodess=()=>{
        // 重置并启动59秒倒计时
        if (timerRef.current) {
            clearInterval(timerRef.current);
            timerRef.current = null;
        }
        let params={
            "loginName":paramsData.loginName,
        }
        getEamilCode(params).then(()=>{
            setDisabled(false);
            global.$toast({
                message:t('t363'),
                callback:()=>{
                    setCountdown(59);
                    timerRef.current = setInterval(() => {
                        setCountdown((prev) => {
                            if (prev <= 1) {
                                clearInterval(timerRef.current);
                                timerRef.current = null;
                                return 0;
                            }
                            return prev - 1;
                        })
                    }, 1000);
                    // TODO: 在此触发重发验证码的实际接口调用（如需要）
                }
            })
        }).catch(err=>{
            setDisabled(false)
        })
    }

    useEffect(()=>{
        StatusBar.setBarStyle('dark-content');
        let params = route.params||{};
        // 如需使用 params，可在此做进一步判空处理
        setParamsData(params as Step2Params);
        return () => {
            if (timerRef.current) {
                clearInterval(timerRef.current);
                timerRef.current = null;
            }
        }
    },[]);
    const CELL_COUNT = 6;
    const [value, setValue] = useState('');
    const ref = useBlurOnFulfill({value, cellCount: CELL_COUNT});
    let [propss, getCellOnLayoutHandler] = useClearByFocusCell({
        value,
        setValue,
    });

    return (
         <View style={{ flex: 1,backgroundColor:"#fff"}}>
            <Headers
                title={''}
                border={false}
                barStyle={0}
                leftTitle={''}
                backgroundColor={'#fff'}
                centerColor={'#666'}
                {...props}
                leftIcon={require('@/assets/images/icon/back.png')}
            />
            <View style={{ flex:1,paddingTop:size(40)}}>
                <View style={styles.form}>
                    <View>
                        <View>
                            <Text style={styles.title}>{t('t374')}</Text>
                        </View>
                        <View>
                            <Text style={styles.subtitle}>{t('t375')}<Text style={styles.subtitletext}>{paramsData.loginName}</Text>{t('t376')}</Text>
                        </View>
                    </View>
                    <View>
                        <CodeField
                            ref={ref}
                            {...props}
                            value={value}
                            onChangeText={setValue}
                            cellCount={CELL_COUNT}
                            rootStyle={styles.codeFieldRoot}
                            keyboardType="number-pad"
                            textContentType="oneTimeCode"
                            renderCell={({index, symbol, isFocused}: {index: number; symbol: string; isFocused: boolean}) => (
                            <Text
                                key={index}
                                style={[styles.cell, isFocused && styles.focusCell]}
                                onLayout={getCellOnLayoutHandler(index)}>
                                {symbol || (isFocused ? <Cursor /> : null)}
                            </Text>
                            )}
                        />
                    </View>
                </View>
            </View>
            <View style={{paddingBottom:size(insets.bottom?insets.bottom:10)}}>
                <View style={[{ marginTop: 20, paddingLeft: size(30), paddingRight: size(30),marginBottom:size(37)}]}>
                    <Button 
                        onClick={() => {
                            onNext();
                        }}
                        disabled={disabled}
                        style={styles.login_box_footer_btn}
                    >
                        <Text style={[styles.login_box_footer_btn_text]}>{t('t255')}</Text>
                    </Button>
                </View>
                <View>
                    <Text style={styles.login_box_footer_text}>{t('t377')}</Text>
                    <Button 
                        onClick={() => {
                            if (countdown === 0) onResendCodess();
                        }}
                        disabled={disabled || countdown > 0}
                        style={styles.loginBox}
                    >
                        <Text style={styles.logincodetext}>{countdown > 0 ? `${countdown}s` : t('t378')}</Text>
                    </Button>
                </View>
               
            </View>
        </View>
    )
}

export default ForgetPasswordStep2Screen;